//
//  GZ_RadioDetailsVC.m
//  B段项目
//
//  Created by 高哲 on 15/11/4.
//  Copyright © 2015年 谢美娜. All rights reserved.
//

#import "GZ_RadioDetailsVC.h"
#import "Header.h"
#import "GZHeaderImageTableViewCell.h"
#import "GZ_PlayerPageVC.h"
#import "GZ_CoreDataManager.h"
#import "RadioModel.h"
@interface GZ_RadioDetailsVC ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataSourceArray;
@property(nonatomic, strong)XMN_ProgressHUD *progressView;

@property(nonatomic,strong)NSString *urlString;
@property(nonatomic, strong)NSString *bodyString;
@property(nonatomic, assign)NSInteger start;

@property(nonatomic, strong)UIBarButtonItem *button;
@property(nonatomic, assign)NSInteger flag;

@property(nonatomic, strong)GZ_CoreDataManager *manager;
@property(nonatomic, strong)NSArray *coreDataArray;

@end

@implementation GZ_RadioDetailsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _progressView = [[XMN_ProgressHUD alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, Height)];
    _progressView.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
    _progressView.XMN_label.text = @"Waiting...";
    [self.view addSubview:_progressView];

   }

- (void)loadView
{
    [super loadView];
    _flag = 0;
    
    _manager = [GZ_CoreDataManager shareManager];
   
    //收藏按钮
    _button = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"GZshoucang.png"] style:UIBarButtonItemStylePlain target:self action:@selector(shoucangAction)];
    _button.tintColor = [UIColor whiteColor];
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"RadioModel"];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"radioid = %@", _radioModel.radioid];
    [fetchRequest setPredicate:predicate];
    _coreDataArray = [_manager.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    
    for (RadioModel *model in _coreDataArray) {
        if ([model.radioid isEqualToString:_radioModel.radioid]) {
            
            _button.tintColor = [UIColor redColor];
            _flag = 1;
            break;
        }else{
            
            _button.tintColor = [UIColor whiteColor];
            _flag = 0;
        }

    }
    
       self.navigationItem.rightBarButtonItem = _button;
    
    
    _urlString = @"http://api2.pianke.me/ting/radio_detail";
    _bodyString = [NSString stringWithFormat:@"auth=&client=1&deviceid=DE384365-C3F9-468E-8E1A-3E78693E4D79&radioid=%@&version=3.0.6", _radioString];
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView NightWithType:UIViewColorType2];
    [self.view addSubview:_tableView];
_dataSourceArray = [NSMutableArray array];
    
    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _start = 0;
        [self getData];
    }];
    _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _start += 10;
        [self getData];
    }];

    [_tableView.header beginRefreshing];
    
    [self getData];
    
    
  
}

- (void)getData
{
    if (_start == 0) {
        _urlString = @"http://api2.pianke.me/ting/radio_detail";
        _bodyString = [NSString stringWithFormat:@"auth=&client=1&deviceid=DE384365-C3F9-468E-8E1A-3E78693E4D79&radioid=%@&version=3.0.6", _radioString];
        
    }else{
        _urlString = @"http://api2.pianke.me/ting/radio_detail_list";
        _bodyString = [NSString stringWithFormat:@"auth=&client=1&deviceid=DE384365-C3F9-468E-8E1A-3E78693E4D79&limit=10&radioid=%@&start=%ld&version=3.0.6", _radioString, _start];
    }

    
 [HTTPMethod getDataByString:_urlString BODYDic:[ChangeString changeStringToDictionary:_bodyString] WithDataBlock:^(id data) {
     
     NSDictionary *dataDic = [data valueForKey:@"data"];
     
    
     
     if (!_start) {
         [_dataSourceArray removeAllObjects];
         //头视图
         NSDictionary *radioInfoDic = [dataDic valueForKey:@"radioInfo"];
         self.title = [radioInfoDic valueForKey:@"title"];
         myView *bgView = [[myView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 315 * FitHeight)];
         
         UIImageView *bigImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 180 * FitHeight)];
         [bigImageView sd_setImageWithURL:[NSURL URLWithString:[radioInfoDic valueForKey:@"coverimg"]] placeholderImage:[UIImage imageNamed:@"GZ_scroll.png"]];
         [bgView addSubview:bigImageView];
         
         UIImageView *userImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20 * FitWidth,bigImageView.frame.size.height + bigImageView.frame.origin.y + 20 * FitHeight, 40 * FitWidth, 40 * FitHeight)];
         userImageView.layer.masksToBounds = YES;
         userImageView.layer.cornerRadius = userImageView.frame.size.width / 2;
        
         [userImageView sd_setImageWithURL:[NSURL URLWithString:[[radioInfoDic valueForKey:@"userinfo"] valueForKey:@"icon"]] placeholderImage:[UIImage imageNamed:@"GZ_Cell.png"]];
         [bgView addSubview:userImageView];
         
         UILabel *nameLable = [[UILabel alloc] initWithFrame:CGRectMake(userImageView.frame.size.width + userImageView.frame.origin.x + 10 * FitWidth, userImageView.frame.origin.y, 150 * FitWidth, 40 * FitHeight)];
         nameLable.textAlignment = NSTextAlignmentLeft;
         nameLable.textColor = [UIColor colorWithRed:0.17 green:0.33 blue:0.54 alpha:1];
         nameLable.text = [[radioInfoDic valueForKey:@"userinfo"] valueForKey:@"uname"];
         nameLable.font = [UIFont systemFontOfSize:14];
         [bgView addSubview:nameLable];
         
         UILabel *descLable = [[UILabel alloc] initWithFrame:CGRectMake(userImageView.frame.origin.x, userImageView.frame.origin.y + userImageView.frame.size.height + 20 * FitHeight, ScreenWidth - 2 * userImageView.frame.origin.x, 25)];
         descLable.textColor = [UIColor lightGrayColor];
         descLable.textAlignment = NSTextAlignmentLeft;
         descLable.text = [radioInfoDic valueForKey:@"desc"];
         descLable.font = [UIFont systemFontOfSize:15];
         [bgView addSubview:descLable];
         
         UIImageView *singIconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(nameLable.frame.size.width + nameLable.frame.origin.x + 40 * FitWidth, nameLable.frame.origin.y + 12 * FitHeight, 20 * FitWidth, 20 * FitHeight)];
         singIconImageView.image = [UIImage imageNamed:@"GZguangbo.png"];
         [bgView addSubview:singIconImageView];
         
         UILabel *peopleLable = [[UILabel alloc] initWithFrame:CGRectMake(singIconImageView.frame.size.width + singIconImageView.frame.origin.x + 5 * FitWidth, singIconImageView.frame.origin.y + 3 * FitHeight, 80 * FitWidth, 20 * FitHeight)];
         peopleLable.textAlignment = NSTextAlignmentLeft;
         peopleLable.textColor = [UIColor lightGrayColor];
         peopleLable.text = [NSString stringWithFormat:@"%@", [radioInfoDic valueForKey:@"musicvisitnum"]];
         peopleLable.font = [UIFont systemFontOfSize:13];
         [bgView addSubview:peopleLable];
         
         UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, bgView.frame.size.height - 1, ScreenWidth, 1)];
         lineView.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
         [bgView addSubview:lineView];
         
         _tableView.tableHeaderView = bgView;
    
         NSArray *listArray = [dataDic valueForKey:@"list"];
         for (NSDictionary *listDic in listArray) {
             GZ_RadioModel *radioModel = [[GZ_RadioModel alloc] init];
             [radioModel setValuesForKeysWithDictionary:listDic];
             [_dataSourceArray addObject:radioModel];
         }

     }
     else{
         
         NSArray *listArray = [dataDic valueForKey:@"list"];
         for (NSDictionary *listDic in listArray) {
             GZ_RadioModel *radioModel = [[GZ_RadioModel alloc] init];
             [radioModel setValuesForKeysWithDictionary:listDic];
             [_dataSourceArray addObject:radioModel];
         
     }
     }
     [_tableView.header endRefreshing];
     [_tableView.footer endRefreshing];

     
          [_progressView removeFromSuperview];
     [_tableView reloadData];
     
 }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GZ_PlayerPageVC *ppvc = [[GZ_PlayerPageVC alloc] init];
   ppvc.dataSourceArray = _dataSourceArray;
    ppvc.tingString = [_dataSourceArray[indexPath.row] tingid];
    ppvc.tempString = _tempString;
    ppvc.radioModel = _dataSourceArray[indexPath.row];
    ppvc.currentIndexpathRow = indexPath.row;
    [self.navigationController pushViewController:ppvc animated:YES];
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100 * FitHeight;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"GZ";
    GZHeaderImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[GZHeaderImageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    if (_dataSourceArray.count != 0) {
        cell.radioModel = _dataSourceArray[indexPath.row];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.2);
    [UIView animateWithDuration:0.5 animations:^{
        cell.layer.transform = CATransform3DMakeScale(1, 1, 0.2);
    }];
    

    return cell;
}

//收藏按钮
- (void)shoucangAction
{
    if (_flag == 0) {
        //alert 新的用法
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定收藏吗?" preferredStyle:UIAlertControllerStyleAlert];
       
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            _button.tintColor = [UIColor redColor];
            _flag = 1;
            
            RadioModel *model = [NSEntityDescription insertNewObjectForEntityForName:@"RadioModel" inManagedObjectContext:_manager.managedObjectContext];
            model.radioid = _radioModel.radioid;
            model.desc = _radioModel.desc;
            model.title = _radioModel.title;
            model.userinfo = [NSKeyedArchiver archivedDataWithRootObject:_radioModel.userinfo];
            model.isnew = [NSNumber numberWithBool:_radioModel.isnew];
            
            model.coverimg = _radioModel.coverimg;
            model.count = [NSString stringWithFormat:@"%@", _radioModel.count];
        
            [_manager saveContext];
            
        }];
        UIAlertAction *alertAction2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            nil;
        }];
        [alert addAction:alertAction];
        [alert addAction:alertAction2];
        [self presentViewController:alert animated:YES completion:nil];
    }
    else {
        
        UIAlertController *alert11 = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定取消收藏吗?😢" preferredStyle:UIAlertControllerStyleAlert];
      
        UIAlertAction *alertAction11 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
          
            _button.tintColor = [UIColor whiteColor];
            _flag = 0;
            
            NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"RadioModel"];
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"radioid = %@", _radioModel.radioid];
            [fetchRequest setPredicate:predicate];
            _coreDataArray = [_manager.managedObjectContext executeFetchRequest:fetchRequest error:nil];
            
            RadioModel *p = [_coreDataArray lastObject];
            [_manager.managedObjectContext deleteObject:p];
            [_manager saveContext];
            
            
        }];
        UIAlertAction *alertAction22 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            nil;
        }];
        
        [alert11 addAction:alertAction11];
        [alert11 addAction:alertAction22];
        [self presentViewController:alert11 animated:YES completion:nil];
    }

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
